let mongoose = require('mongoose')
mongoose.set('strictQuery', true);
mongoose.connect("mongodb://127.0.0.1/epi_thesis")
let Schema = mongoose.Schema
const {allWords} = require('../data_mock/wordColud')
const {getYear} = require("./province_sales");

let wordSchema = new Schema({
    word:{
        type:String,
        required:true
    },
    number:{
        type:Number,
        required: true
    },
    year:{
        type:String,
        required:true
    }
})

let wordModel = mongoose.model('wordCloud', wordSchema,'wordCloud')

/*const wordsModel = () => {
    for (let i = 0; i < allWords.length;i++) {
        try{
            console.log(allWords[i],i)
            wordModel.insertMany(allWords[i])
            console.log(`数据插入中--------${i}/${allWords.length}`)
        }catch (e) {

        }
    }
}
const test = async () => {
    await wordsModel()
}
test()*/

const getWordModel = async () => {
    let time = await getYear()
    let allData = []
    for (let i = 0; i < time.length; i++) {
        let getData = () => {
            return wordModel.find({year: time[i]})
                .then(res => {
                    let data = []
                    res.map(item => {
                        data.push({'name':item.word,'value':item.number})
                    })
                    return {data,'year':time[i]}
                })
                .catch(err => {
                    console.log(err)
                    return false
                })
        }
        allData.push(await getData())
    }
    // return JSON.parse(JSON.stringify(allData)).sort((a,b)=>{
    //     return a.year.slice(0,4) - b.year.slice(0,4)
    // })
    return allData
}

module.exports = {getWordModel}
